import 'package:auto_route/auto_route.dart';
import 'package:casdon/app/config/theme/theme_extention.dart';
import 'package:casdon/build_gen/assets.gen.dart';
import 'package:casdon/common/service/tuya_service.dart';
import 'package:casdon/common/widget/common_app_bar.dart';
import 'package:casdon/core/logger/log.dart';
import 'package:casdon/auto_router.dart';

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:tuya_home_sdk_flutter/tuya_home_sdk_flutter.dart';

enum DeviceSetupStep { authentication, networking, cloud, success }

final setupStepProvider = StateProvider.autoDispose<DeviceSetupStep>(
  (ref) => DeviceSetupStep.authentication,
);

@RoutePage()
class QrDeviceProgressScreen extends ConsumerStatefulWidget {
  final String qrcode;

  const QrDeviceProgressScreen({super.key, required this.qrcode});

  @override
  ConsumerState<QrDeviceProgressScreen> createState() =>
      _AddDeviceProgressScreenState();
}

class _AddDeviceProgressScreenState
    extends ConsumerState<QrDeviceProgressScreen>
    with TickerProviderStateMixin {
  late AnimationController _mainIconController;
  late AnimationController _stepIconController;
  late AnimationController _currentStepController;

  // QR 进度页仅展示 UI，不注入外部配网 notifier 逻辑

  @override
  void initState() {
    super.initState();

    // 主图标旋转控制器（2秒/圈）
    _mainIconController = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 2),
    )..repeat();

    // 步骤图标旋转控制器（1秒/圈）
    _stepIconController = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 1),
    )..repeat();

    // 当前步骤高亮动画控制器
    _currentStepController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 300),
    );
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _currentStepController.forward();
    });
    _tuyaCodePairNet(widget.qrcode);
  }

  @override
  void dispose() {
    _mainIconController.dispose();
    _stepIconController.dispose();
    _currentStepController.dispose();
    super.dispose();
  }

  // 预留：模拟步骤或失败/成功跳转逻辑可由外层触发时再补充

  // 预留：成功跳转逻辑可由外层集成时实现

  @override
  Widget build(BuildContext context) {
    final currentStep = ref.watch(setupStepProvider);
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: CommonAppBar(title: "添加设备"),
      body: Padding(
        padding: const EdgeInsets.all(24.0),
        child: Column(
          children: [
            // 标题和提示
            Text(
              '正在添加设备',
              style: const TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
                color: Colors.black,
              ),
            ),
            SizedBox(height: 8.h),
            const Text(
              '确保Wi-Fi信号良好',
              style: TextStyle(fontSize: 14, color: Colors.grey),
            ),
            SizedBox(height: 40.h),

            Stack(
              alignment: Alignment.center,
              children: [
                RotationTransition(
                  turns: _mainIconController,
                  child: Image.asset(
                    Assets.images.pairNetIng.path,
                    width: 248.w,
                    height: 248.w,
                  ),
                ),

                Image.asset(
                  Assets.images.icNetRouter.path,
                  width: 84.w,
                  height: 84.w,
                ),
              ],
            ),
            SizedBox(height: 40.h),

            // 步骤进度条
            _buildProgressSteps(currentStep),
          ],
        ),
      ),
    );
  }

  Widget _buildProgressSteps(DeviceSetupStep currentStep) {
    return SizedBox(
      height: 80.h, // 固定高度包含线和步骤内容
      child: Stack(
        children: [
          // 底部贯穿线
          Positioned(
            left: 34, // 左边距
            right: 34, // 右边距
            top: 23, // 调整到图标下方
            child: Container(
              height: 2,
              color: context.colorScheme.primary, // 基线颜色
            ),
          ),

          // 步骤内容
          Positioned.fill(
            child: Row(
              children: [
                Expanded(
                  child: _buildStepItem(
                    '设备认证',
                    isCompleted:
                        currentStep.index >
                        DeviceSetupStep.authentication.index,
                    isCurrent: currentStep == DeviceSetupStep.authentication,
                    // isFirst: true,
                  ),
                ),
                Expanded(
                  child: _buildStepItem(
                    '设备联网',
                    isCompleted:
                        currentStep.index > DeviceSetupStep.networking.index,
                    isCurrent: currentStep == DeviceSetupStep.networking,
                  ),
                ),
                Expanded(
                  child: _buildStepItem(
                    '设备入云',
                    isCompleted:
                        currentStep.index > DeviceSetupStep.cloud.index,
                    isCurrent: currentStep == DeviceSetupStep.cloud,
                  ),
                ),
                Expanded(
                  child: _buildStepItem(
                    '设备成功',
                    isCompleted: currentStep == DeviceSetupStep.success,
                    isCurrent: currentStep == DeviceSetupStep.success,
                    // isLast: true,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildStepItem(
    String title, {
    required bool isCompleted,
    required bool isCurrent,
  }) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 12),
      child: Column(
        children: [
          // 步骤图标
          AnimatedContainer(
            duration: const Duration(milliseconds: 300),
            width: 24,
            height: 24,
            child: isCompleted
                ? Image.asset(
                    Assets.images.stepOk.path,
                    width: 24.w,
                    height: 24.w,
                  )
                : isCurrent
                ? RotationTransition(
                    turns: _stepIconController,
                    child: Image.asset(
                      Assets.images.stepIng.path,
                      width: 24.w,
                      height: 24.w,
                    ),
                  )
                : Image.asset(
                    Assets.images.stepIdle.path,
                    width: 24.w,
                    height: 24.w,
                  ),
          ),
          const SizedBox(width: 16),
          SizedBox(height: 5),
          // 步骤文本
          AnimatedDefaultTextStyle(
            duration: const Duration(milliseconds: 300),
            style: TextStyle(
              fontSize: 14,
              fontWeight: isCurrent ? FontWeight.w500 : FontWeight.normal,
              color: isCurrent
                  ? context.colorScheme.primary
                  : context.customColorThemeNonNull.textColor3,
            ),
            child: Text(title),
          ),
        ],
      ),
    );
  }

  void _tuyaCodePairNet(String qrcode) async {
    // 监听状态变化并执行相应操作
    final device = await TuyaService().startConfigQRCodeDevice(
      qrCode: qrcode,
      ssid: '', // 涂鸦二维码配网实际就是确权，不需要ssid和密码
      password: '',
    );
    if (device != null) {
      Log.i('🎉 设备配网成功，记录uuid: ${device.uuid}');
      _simulateSetupProcess(device);
    } else {
      Log.e('❌ 设备配网失败', Object(), StackTrace.current);
      _goPairNetFailedScreen();
    }
  }

  void _simulateSetupProcess(ThingSmartDeviceModel devModel) async {
    // 第一步：设备认证（立即开始动画）
    if (!mounted) return;
    ref.read(setupStepProvider.notifier).state = DeviceSetupStep.authentication;
    await Future.delayed(const Duration(seconds: 2));

    // 第二步：设备联网
    if (!mounted) return;
    ref.read(setupStepProvider.notifier).state = DeviceSetupStep.networking;
    await Future.delayed(const Duration(seconds: 1));

    // 第三步：设备入云
    if (!mounted) return;
    ref.read(setupStepProvider.notifier).state = DeviceSetupStep.cloud;
    await Future.delayed(const Duration(seconds: 2));

    // 第四步：设备成功
    if (!mounted) return;
    ref.read(setupStepProvider.notifier).state = DeviceSetupStep.success;
    await Future.delayed(const Duration(seconds: 1));

    // 跳转到成功页面
    if (!mounted) return;
    _goPairNetSuccessScreen(devModel);
  }

  void _goPairNetFailedScreen() {
    if (!mounted) return;
    PairnetFailedRoute(isQrPairNet: true).push(context);
  }

  void _goPairNetSuccessScreen(ThingSmartDeviceModel devModel) async {
    if (!mounted) return;
    PairnetSuccessRoute(devId: devModel.devId!).push(context);
  }
}
